/*--------------------------------------------------------------
 * File: data.c 编码类型：C语言  UTF-8
 * Author WRS (1352509846@qq.com)
 * 功能: 数据生成功能
 * Version 0.1
 * Date 2024-04-26 
 * 
 * @copyright Copyright (c) 2024
 * 
----------------------------------------------------------------*/
#include "user_Modbus.h"
#include "esp_log.h"

#include "mdns.h"
#include "esp_netif.h"

#include "mbcontroller.h"       // for mbcontroller defines and api

#define MB_TCP_PORT_NUMBER      (502)   // modbusTCP使用端口

static const char *TAG = "userModbus ";

mb_communication_info_t comm_info = { 0 };

void user_Modbus_init(void)
{
    comm_info.ip_addr_type = MB_IPV4;
    comm_info.ip_mode = MB_MODE_TCP;
    comm_info.ip_port = MB_TCP_PORT_NUMBER;
    comm_info.ip_addr = NULL; // Bind to any address
    comm_info.ip_netif_ptr = (void*)esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");   // 获取网络接口

    // Initialization of Modbus controller
    void* slave_handler = NULL;
    esp_err_t err = mbc_slave_init_tcp(&slave_handler);
    // MB_RETURN_ON_FALSE((err == ESP_OK && slave_handler != NULL), ESP_ERR_INVALID_STATE,
    //                             TAG,
    //                             "mb controller initialization fail.");

    // Setup communication parameters and start stack
    err = mbc_slave_setup((void*)&comm_info);
    // MB_RETURN_ON_FALSE((err == ESP_OK), ESP_ERR_INVALID_STATE,
    //                                     TAG,
    //                                     "mbc_slave_setup fail, returns(0x%x).",
    //                                     (uint32_t)err);
    // 添加modbus寄存器的初始化---------------------------------

    // 添加modbus寄存器的初始化---------------------------------  
}

/*--------------------------------------------------------------
 * 功能: modbus从站启动
 * 注：必须在初始化完成后再启动，启动前还要配置一modbus的寄存器
----------------------------------------------------------------*/
esp_err_t user_Modbus_slave_start(void)
{
    // Starts of modbus controller and stack
    esp_err_t err = mbc_slave_start();
    if (err != ESP_OK)
    {
        ESP_LOGE(TAG, "Failed to sttart Modbus slave: %s", esp_err_to_name(err));
    }
    return err;
}

esp_err_t user_Modbus_slave_destroy(void)
{
    esp_err_t err = mbc_slave_destroy();
    if (err != ESP_OK)
    {
        ESP_LOGE(TAG, "Failed to stop Modbus slave: %s", esp_err_to_name(err));
    }
    return err;
}
